package org.example;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.*;
import java.io.*;

public class BB_UINT16 {

    public static void main(String[] args) throws IOException {
        String inputPngPath = "D:\\Documents\\workspaces\\Gitee\\java-projects\\untitled\\src\\main\\resources\\ame\\Snipaste.png";
        String outputRawPath = "output.raw";
        String outputPngPath = "output.png";

        // 步骤1: 读取PNG图片
        BufferedImage pngImage = ImageIO.read(new File(inputPngPath));

        // 步骤2: 转换PNG到16位黑白RAW
        convertToRaw16Grayscale(pngImage, outputRawPath);

        // 步骤4: 读取RAW文件并转换回PNG
        BufferedImage rawImage = convertFromRaw16Grayscale(outputRawPath, pngImage.getWidth(), pngImage.getHeight());
        ImageIO.write(rawImage, "png", new File(outputPngPath));
    }

    private static void convertToRaw16Grayscale(BufferedImage image, String outputPath) throws IOException {
        int width = image.getWidth();
        int height = image.getHeight();
        BufferedImage grayscaleImage = new BufferedImage(width, height, BufferedImage.TYPE_BYTE_GRAY);
        Graphics2D g = grayscaleImage.createGraphics();
        g.drawImage(image, 0, 0, null);
        g.dispose();

        // 获取灰度图像的像素数据
        byte[] pixels = ((DataBufferByte) grayscaleImage.getRaster().getDataBuffer()).getData();

        // 创建16位RAW图像数据
        short[] rawPixels = new short[width * height];
        for (int i = 0; i < pixels.length; i++) {
            // 将8位灰度值扩展到16位
            rawPixels[i] = (short) ((pixels[i] & 0xFF) << 8);
        }

        // 步骤3: 保存RAW文件
        try (DataOutputStream dos = new DataOutputStream(new FileOutputStream(outputPath))) {
            for (short pixel : rawPixels) {
                dos.writeShort(pixel);
            }
        }
    }

    private static BufferedImage convertFromRaw16Grayscale(String inputPath, int width, int height) throws IOException {
        // 步骤4: 读取RAW文件
        short[] rawPixels = new short[width * height];
        try (DataInputStream dis = new DataInputStream(new FileInputStream(inputPath))) {
            for (int i = 0; i < rawPixels.length; i++) {
                rawPixels[i] = dis.readShort();
            }
        }

        // 创建新的灰度图像
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_USHORT_GRAY);
        WritableRaster raster = image.getRaster();
        DataBuffer dataBuffer = raster.getDataBuffer();
        if (dataBuffer instanceof DataBufferUShort) {
            short[] pixels = ((DataBufferUShort) dataBuffer).getData();
            System.arraycopy(rawPixels, 0, pixels, 0, rawPixels.length);
        }

        return image;
    }
}
